package org.pz.service;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import org.pz.dto.DatasourceDto;
import org.pz.mapper.DataSourceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.List;

@Service
public class DataSourceService {

    @Resource
    DynamicRoutingDataSource dataSource;

    @Autowired
    private DataSourceMapper dataSourceMapper;

    /**
     * 添加数据源
     * */
    public void addDataSource(DatasourceDto dto) {

        addDynamicDataSource(dto);

        //3. 添加到 sql 中去
        dataSourceMapper.addDataSource(dto);
    }

    /**
     * 初始化数据源
     * */
    public void initDatasource() {
        List<DatasourceDto> list = dataSourceMapper.findDataSource();
        for(DatasourceDto dto : list) {
            addDynamicDataSource(dto);
        }
    }

    /**
     * 获取数据源列表
     * */
    public List<DatasourceDto> list(){
        return dataSourceMapper.findDataSource();
    }

    private void addDynamicDataSource(DatasourceDto dto){
        //1. 根据参数创建数据源
        DataSource ds = DataSourceBuilder.create()
                .url(dto.getUrl())
                .username(dto.getUsername())
                .password(dto.getPassword())
                //这里应该分多种数据源，这里省事了，只玩 mysql
                .driverClassName("com.mysql.cj.jdbc.Driver")
                .build();

        //2. 添加到动态数据源中
        dataSource.addDataSource(dto.getLogotype(), ds);
    }
}
